package br.com.ridea.pegadacultural.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import br.com.ridea.pegadacultural.dto.EnderecoDTO;
import br.com.ridea.pegadacultural.facade.ExperienciaFacade;
import br.com.ridea.pegadacultural.form.ExperienciaForm;
import br.com.ridea.pegadacultural.model.Experiencia;
import br.com.ridea.pegadacultural.utilidades.EstadosBrasilEnum;
import br.com.ridea.pegadacultural.utilidades.TreatDate;
import br.com.ridea.pegadacultural.utilidades.Validator;
import br.com.ridea.pegadacultural.utils.Mensagem;

import com.google.gson.Gson;

public class ExperienciaAction extends DispatchAction {

	public ActionForward iniciarProcesso( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		ExperienciaForm form = (ExperienciaForm) actionForm;
		try{
			form.reset(mapping, request);
			
			form.setExperienciasDTO(ExperienciaFacade.listar());
			
		}catch (Exception e) {
			form.addMensagem(request, Mensagem.ERRO, e.getMessage());
		}
		return mapping.findForward( "pgConsulta" );
	}
	
	public ActionForward abrirTelaIncluir( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		ExperienciaForm form = (ExperienciaForm) actionForm;
		try{
			form.reset(mapping, request);
			form.setEstados(EstadosBrasilEnum.listar());
		}catch (Exception e) {
			form.addMensagem(request, Mensagem.ERRO, e.getMessage());
		}
		return mapping.findForward( "pgEdit" );
	}
	
	public ActionForward incluir( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		ExperienciaForm form = (ExperienciaForm) actionForm;
		try{
			
			//TODO pegar promoter logado
			
			
			form.getExperiencia().setDataHoraInicio(form.getDataInicio() + " " + form.getHoraInicio());
			form.getExperiencia().setDataHoraInicio(form.getDataFim() + " " + form.getHoraFim());
			
			ExperienciaFacade.inserir(form.getExperiencia().getExperiencia());
			
		}catch (Exception e) {
			form.addMensagem(request, Mensagem.ERRO, e.getMessage());
		}
		return mapping.findForward( "pgConsulta" );
	}
	
	public ActionForward abrirTelaAlterar( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		ExperienciaForm form = (ExperienciaForm) actionForm;
		try{
			form.setEstados(EstadosBrasilEnum.listar());
			
			Experiencia experiencia = ExperienciaFacade.obter(form.getCodigoExpeciencia());
			
			form.setDataInicio(TreatDate.format("dd/MM/yyyy", experiencia.getDataHoraInicio()));
			form.setDataFim(TreatDate.format("dd/MM/yyyy", experiencia.getDataHoraTermino()));
			form.setHoraInicio(TreatDate.format("HH:mm", experiencia.getDataHoraInicio()));
			form.setHoraFim(TreatDate.format("HH:mm", experiencia.getDataHoraTermino()));
			
			form.setExperiencia(experiencia.getExperienciaDTO());
		}catch (Exception e) {
			form.addMensagem(request, Mensagem.ERRO, e.getMessage());
		}
		return mapping.findForward( "pgEdit" );
	}
	
	public ActionForward alterar( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		ExperienciaForm form = (ExperienciaForm) actionForm;
		try{
			
			//TODO pegar promoter logado
			
			
			form.getExperiencia().setDataHoraInicio(form.getDataInicio() + " " + form.getHoraInicio());
			form.getExperiencia().setDataHoraInicio(form.getDataFim() + " " + form.getHoraFim());
			
			ExperienciaFacade.alterar(form.getExperiencia().getExperiencia());
			
		}catch (Exception e) {
			form.addMensagem(request, Mensagem.ERRO, e.getMessage());
		}
		return mapping.findForward( "pgConsulta" );
	}
	

	public void adicionarEndereco( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response ) {
		ExperienciaForm form = (ExperienciaForm) actionForm;
		form.limparMensagem(request);
		String json = "";
		try {
			Validator val =  Validator.novo();

			form.getEndereco().validar();
//			form.getEndereco().setEnums();

			if(val.isNullOrZero(form.getEndereco().getCodigo())){
				form.getListaEnderecos().add(form.getEndereco());
			}else{
				for (EnderecoDTO end : form.getListaEnderecos()) {
					if(form.getEndereco().getCodigo().equals(end.getCodigo())){
						end.setBairro(form.getEndereco().getBairro());
						end.setCep(form.getEndereco().getCep() != null ? form.getEndereco().getCep() : "");
						end.setCidade(form.getEndereco().getCidade());
						end.setLogradouro(form.getEndereco().getLogradouro());
						end.setNumero(form.getEndereco().getNumero());
						end.setUf(form.getEndereco().getUf());
//						end.setEnums();
					}
				}
			}

			form.setEndereco(new EnderecoDTO());

			Gson gson = new Gson();
			json = gson.toJson(form.getListaEnderecos());
			response.getWriter().write( json );
		} catch ( Exception e ) {
			try {
				response.getWriter().write( json );
			} catch (IOException e1) {
				form.addMensagem(request, Mensagem.ERRO, e.getMessage());
			}
		}

	}

	public void editarEndereco( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response ) {
		ExperienciaForm form = (ExperienciaForm) actionForm;
		form.limparMensagem(request);
		String json = "";
		try {
			form.setEndereco(new EnderecoDTO());

			Gson gson = new Gson();

			for (EnderecoDTO end : form.getListaEnderecos()) {
				if(form.getCodigoEndereco().equals(end.getCodigo())){
					json = gson.toJson(new ArrayList<EnderecoDTO>(Arrays.asList(end) ));
					break;
				}
			}

			response.getWriter().write( json );
		} catch ( Exception e ) {
		}

	}

	public void excluirEnderecoIndex( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response ) {
		ExperienciaForm form = (ExperienciaForm) actionForm;
		form.limparMensagem(request);
		String json = "";
		try {
			Integer index = null;
			for(int i= 0; i < form.getListaEnderecos().size(); i++){
				if(i == form.getIndexEndereco().intValue()){
					index = i;
					break;
				}
			}
			if(index != null)
				form.getListaEnderecos().remove(index.intValue());

			form.setEndereco(new EnderecoDTO());

			Gson gson = new Gson();
			json = gson.toJson(form.getListaEnderecos());
			response.getWriter().write( json );
		} catch ( Exception e ) {
		}

	}

	public void excluirEnderecoCodigo( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response ) {
		ExperienciaForm form = (ExperienciaForm) actionForm;
		form.limparMensagem(request);
		String json = "";
		try {
			if(form.getEnderecoExcluir() == null)
				form.setEnderecoExcluir(new ArrayList<EnderecoDTO>());

			Integer index = null;
			for(int i= 0; i < form.getListaEnderecos().size(); i++){
				EnderecoDTO dto = form.getListaEnderecos().get(i);
				if(dto.getCodigo() != null && dto.getCodigo().equals(form.getCodigoEndereco())){
					form.getEnderecoExcluir().add(dto);
					index = i;
					break;
				}
			}
			if(index != null)
				form.getListaEnderecos().remove(index.intValue());

			form.setEndereco(new EnderecoDTO());

			Gson gson = new Gson();
			json = gson.toJson(form.getListaEnderecos());
			response.getWriter().write( json );
		} catch ( Exception e ) {
		}

	}
}
